package com.power.weboffice.dao.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.plf.core.common.dao.OffersetTransformers;
import com.power.weboffice.dao.WebOfficeCallbackDao;
import org.hibernate.query.internal.NativeQueryImpl;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;

@Repository
public class WebOfficeCallbackDaoImpl implements WebOfficeCallbackDao {

    private final EntityManager entityManager;

    public WebOfficeCallbackDaoImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public String getAttachmentByPath(String path) {
        String sql ="select id from ha_attachment where path like ?";
        Query query = entityManager.createNativeQuery((sql));
        query.unwrap(NativeQueryImpl.class).setResultTransformer(OffersetTransformers.ALIAS_TO_ENTITY_MAP);
        query.setParameter(1, "%" + path + "%");
        List resultList = query.getResultList();
        if (CollectionUtil.isNotEmpty(resultList)) {
            Map result = JSON.parseObject(JSON.toJSONString(resultList.get(0)), Map.class);
            return (String) result.get("id");
        }
        return null;
    }
}
